package com.le.tester.leetcode;

import com.le.tester.leetcode.common.ListNode;

import java.util.Arrays;

/**
 * 描述：合并两个有序的链表
 */
public class MergeListOrder {
    public ListNode mergeTwoListsLoop(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(-1);
        //自己定义一个链表头
        ListNode preNode = result;

        while (null != l1 && null != l2) {
            if (l1.val <= l2.val) {
                //先操作head,不要想着val
                preNode.next = l1;
                //现在自己就是链表的头了
                l1 = l1.next;
            } else {
                preNode.next = l2;
                l2 = l2.next;
            }
            preNode = preNode.next;
        }
        //注意要全部合并完，不要null
        preNode.next = l1 == null ? l2 : l1;
        return result.next;
    }

    public ListNode mergeTwoListsRecursion(ListNode l1, ListNode l2) {
        //递归比较数据的值
        if (null == l1) {
            return l2;
        } else if (null == l2) {
            return l1;
        } else if (l1.val < l2.val) {
            l1.next = mergeTwoListsRecursion(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoListsRecursion(l1, l2.next);
            return l2;
        }
    }

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
//        listNode1.next.val = 2;
//        listNode1.next.next.val = 3;

        ListNode listNode2 = new ListNode(1);
//        listNode2.next.val = 2;
//        listNode2.next.next.val = 4;
        MergeListOrder mergeListOrder = new MergeListOrder();
        System.out.println(Arrays.asList(mergeListOrder.mergeTwoListsRecursion(listNode1, listNode2)));
    }
}
